<?php


namespace App\Models\Traits;


use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

trait LastActivedAtHelper
{
    // 缓存相关
    protected $hash_prefix = 'larabbs_last_actived_at_';
    protected $field_prefix = 'user_';

    public function recordLastActiveAt()
    {   //当前日期
        // Redis 哈希表的命名，如：larabbs_last_actived_at_2017-10-21
        $hash = $this->getHashFromNowStr();
        // 字段名称，如：user_1
        $field = $this->getField();

        // 当前时间，如：2017-10-21 08:35:15
        $now = Carbon::now()->toDateTimeString();

        // 数据写入 Redis ，字段已存在会被更新
        Redis::hSet($hash, $field, $now);
    }

    public function syncUserActivedAt()
    {
        // Redis 哈希表的命名，如：larabbs_last_actived_at_2017-10-21
        $hash = $this->hash_prefix . Carbon::yesterday()->toDateString();
        // 从 Redis 中获取所有哈希表里的数据
        $dates = Redis::hGetAll($hash);

        foreach ($dates as $user_id => $active_at) {
            $user_id = str_replace($this->field_prefix, "", $user_id);
            if ($user = User::find($user_id)) {
                $user->last_actived_at = $active_at;
                $user->save();
            }
        }
        //
        Redis::del($hash);
    }

    public function getLastActivedAtAttribute($value)
    {
        $hash = $this->getHashFromNowStr();
        $field = $this->getField();
        //缓存有取缓存，没有取数据库
        $dateTime = Redis::hget($hash, $field) ?: $value;
        if ($dateTime) {
            return new Carbon($dateTime);
        } else {
            //数据库也没有返回注册时间
            return $this->created_at;
        }
    }

    /**
     * @return string
     */
    private function getHashFromNowStr(): string
    {
        return $this->hash_prefix . Carbon::now()->toDateString();
    }

    /**
     * @return string
     */
    private function getField(): string
    {
        return $this->field_prefix . $this->id;
    }
}
